package cn.com.flower.admin.content.service.impl;

import cn.com.flower.admin.content.dao.persist.repository.IArticleRepository;
import cn.com.flower.admin.content.dao.persist.repository.ICategoryRepository;
import cn.com.flower.admin.content.dao.persist.repository.ICategoryRepository;
import cn.com.flower.admin.content.pojo.entity.Category;
import cn.com.flower.admin.content.pojo.param.CategoryAddNewParam;
import cn.com.flower.admin.content.pojo.vo.CategoryStandardVO;
import cn.com.flower.admin.content.service.ICategoryService;
import cn.com.flower.common.enumerator.ServiceCode;
import cn.com.flower.common.ex.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private ICategoryRepository repository;

    @Autowired
    private IArticleRepository articleRepository;

    @Override
    public void delete(Long id) {
        log.debug("开始执行【根据id删除类别】的业务，参数:{}",id);
        CategoryStandardVO currentCategory = repository.getStandardById(id);
        if(currentCategory==null){
            String message="删除类别失败，尝试删除的类别数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        int rows = articleRepository.countByCategory(id);
        if(rows!=1){
            String message="删除类别失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE,message);
        }

        repository.delete(id);
    }
    @Autowired
    ICategoryRepository iCategoryRepository;
    @Override
    public void AddNew(CategoryAddNewParam categoryAddNewParam) {
     String username= categoryAddNewParam.getName();
        int countByName = iCategoryRepository.countByName(username);
        if(countByName>0){
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,"添加类别失败，类别名称已经被占用！");
        }

        Category category = new Category();
        BeanUtils.copyProperties(categoryAddNewParam,category);
        int insert = repository.insert(category);
        if (insert!=1){
            String message = "添加类别失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

    }

    @Override
    public CategoryStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据id查询类别】的业务，参数：{}",id);
        CategoryStandardVO queryResult = repository.getStandardById(id);
        if(queryResult==null){
            String message="查询类别详情失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        return queryResult;
    }
}
